<?php

class Authorization {
    private $db;
    private $tableName;
    function __construct($db_,$tableName_)
    {
        $this->db = $db_;
        $this->tableName = $tableName_;
    }
    function checkAuthorization($showError = true)
    {
        $time = time();
        $acessToken = $_SERVER['HTTP_AUTHORIZATION'] ?? null;
        $result = $this->db->get($this->tableName, ['acessTime', 'id'], ['acessToken' => $acessToken]);// selectSql("`acessToken` = '{$acessToken}'"); //  AND {$time} - `acessTime` < 3600
        $msg = '';
        if ($result) {
            if ($time - $result['acessTime'] <= 3600) {
                return ['status' => 1, 'result' => $result];
            } else {
                $msg = 'acessToken过期';
            }
        } else {
            $msg = 'acessToken不正确';
        }
        if ($showError) {
            header('HTTP/1.1 401 Unauthorized');
            header("status: 401 Unauthorized");
        }
        return ['status' => -1, 'msg' => $msg];
    }
}
